<template>
  <div>
    <el-drawer :title="title" v-model="visible" :size="1000" @close="hide">
      <template #header>
        <div class="flex items-center title">
          <div class="w-[5px] h-[5px] rounded-[50%] bg-[#3721FF] mr-[10px] circle"></div>
          <div class="tits">{{ title }}</div>
        </div>
      </template>
      <div class="w-full h-[1px] bg-[#EFEFEF] line"></div>
      <div class="pt-[30px]">
        <div class="bg-[#FAFAFA] px-[24px] py-[22px] rounded-[4px] formbox">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120"
            require-asterisk-position="right"
            :validate-on-rule-change="false"
          >
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="导出模板名称" prop="name">
                  <template #label>
                    <div class="flex text-[#101010] items-center"> 导出模板名称 </div>
                  </template>
                  <el-input v-model="form.name" placeholder="请输入导出模板名称" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="多sku导出方式" prop="method">
                  <template #label>
                    <div class="flex text-[#101010] items-center"> 多sku导出方式 </div>
                  </template>
                  <el-select v-model="form.method" placeholder="请选择多sku导出方式">
                    <el-option label="多个SKU一行数据，显示多个产品的SKU信息" :value="1" />
                    <el-option label="多个SKU多行数据，只复制订单编号" :value="2" />
                    <el-option label="多个SKU多行数据，复制相同订单信息" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 10px">
              <el-col :span="24">
                <el-form-item label="设置模板字段">
                  <template #label>
                    <div class="flex text-[#101010] items-center">
                      设置模板字段
                      <span class="text-[#F57171]">*</span>
                    </div>
                  </template>
                  <div class="flex items-center val">
                    <div
                      class="bg-[#3721FF] text-[#fff] rounded-[6px] px-[15px] py-[6px] cursor-pointer btn hover:bg-[#6959f9]"
                      @click="handleField"
                    >
                      <Icon icon="ep:plus" :size="12" color="#fff" />
                      添加变量
                    </div>
                    <!-- <div
                      class="ml-[20px] text-[#3721FF] font-medium cursor-pointer btn"
                      @click="handleCustomField"
                    >
                      添加自定义字段
                    </div> -->
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="list">
        <el-table :data="list" ref="table" class="draggable-table">
          <el-table-column label="字段名称" prop="value">
            <template #default="{ row }">
              <div class="flex handle items-center">
                <Icon icon="ep:operation" class="cursor-pointer mr-[4px]" :size="16" color="#999" />
                <el-input
                  v-model="row.value"
                  maxlength="100"
                  :show-word-limit="true"
                  placeholder="请输入字段名称"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="变量名称" prop="label" width="200" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <div class="flex items-center">
                <el-button type="text" size="small" v-if="row.type === 'system'">编辑</el-button>
                <el-button type="text" size="small" @click="delRow(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="hide" style="border-radius: 6px !important; width: 109px"
            >取消</el-button
          >
          <el-button
            type="primary"
            color="#3721FF"
            @click="onSubmit"
            style="border-radius: 6px !important; width: 109px"
            >确定</el-button
          >
        </div>
      </template>
    </el-drawer>
    <Fields ref="fieldsRef" @confirm="getFields" />
  </div>
</template>

<script setup lang="ts">
import Fields from './fields.vue'
import Sortable from 'sortablejs'
import { FormInstance } from 'element-plus'
import * as ExportApi from '@/api/mall/trade/export'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { useUserStore } from '@/store/modules/user'

const emit = defineEmits(['updateList'])

const message = useMessage()

const userStore = useUserStore()

const { loadStart, loadDone } = usePageLoading()

const props = defineProps({
  curRow: {
    type: Object as PropType<ExportApi.ExportItemsVO>,
    default: () => {}
  }
})

type FormType = {
  fieldName: string
  variableName: string
  type: 'system' | 'custom'
}

const formRef = ref<FormInstance | null>(null)

const title = ref('新增模板')

const form = ref({
  createName: userStore.user.nickname ?? 'Admin',
  name: '',
  method: undefined,
  field: '',
  fieldName: ''
})

const rules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  method: [{ required: true, message: '请选择多sku导出方式', trigger: 'change' }]
}

// const list = ref<FormType[]>([])
const list = ref<any[]>([])

const fieldsRef = ref<InstanceType<typeof Fields> | null>(null)

const isQueryed = ref(false)

const visible = ref(false)

watch(
  () => props.curRow,
  (newVal) => {
    if (newVal && newVal.id) {
      title.value = '编辑模板'
      form.value = newVal
      if (form.value.field) {
        const fields = form.value.field.split(',')
        const fieldNames = form.value.fieldName ? form.value.fieldName.split(',') : []
        list.value = fields.map((field, index) => {
          return {
            value: field,
            label: fieldNames[index] || '-',
            colorType: '',
            cssClass: ' '
          }
        })
      }
    } else {
      title.value = '新增模板'
    }
  },
  { immediate: true }
)
/**
 * 检测list中value是否重复
 */
const hasDuplicateValues = (arr) => {
  const valueSet = new Set()

  for (const item of arr) {
    if (valueSet.has(item.value)) {
      return true // 找到重复值
    }
    valueSet.add(item.value)
  }

  return false // 没有重复值
}

/**
 * 提交
 */
const onSubmit = () => {
  formRef.value?.validate(async (bool) => {
    if (bool) {
      if (list.value.length === 0) {
        message.error('请添加字段')
        return
      } else {
        //检查字段是否填写正确
        let isOk = true
        let isRepeat = false
        list.value.map((item) => {
          if (!isOk) return
          if (!item.value) {
            isOk = false
            message.error('请填写字段名称')
            return
          }
        })
        isRepeat = hasDuplicateValues(list.value)
        if (isRepeat) {
          message.error('字段名称不能重复')
          return
        }
      }
      const params = {
        ...form.value,
        field: list.value.map((item) => item.value).join(','),
        fieldName: list.value.map((item) => item.label).join(',')
      }
      try {
        loadStart()
        if (form.value.id) {
          // 编辑
          await ExportApi.updateExport(params)
          message.success('修改成功')
        } else {
          // 添加
          await ExportApi.addExport(params)
          message.success('添加成功')
        }
        emit('updateList')
        hide()
        clearForm()
      } finally {
        loadDone()
      }
    }
  })
}

const clearForm = () => {
  form.value = {
    name: '',
    field: '',
    fieldName: '',
    method: undefined,
    createName: userStore.user.nickname ?? 'Admin'
  }
  list.value = []
  formRef.value?.resetFields()
}

const handleField = () => {
  fieldsRef.value?.show()
}

const handleCustomField = () => {
  list.value.push({
    value: null,
    lable: '',
    colorType: '',
    cssClass: '',
    type: 'custom'
  })
}

const getFields = (val: any) => {
  console.log(val, 'val')
  list.value = val
}

const initSortable = () => {
  nextTick(() => {
    const tbody: HTMLElement | null = document.querySelector(
      '.draggable-table .el-table__body-wrapper tbody'
    )
    tbody &&
      new Sortable(tbody, {
        handle: '.handle', // handle's class
        animation: 150,
        // 需要在odEnd方法中处理原始eltable数据，使原始数据与显示数据保持顺序一致
        onEnd: ({ newIndex, oldIndex }) => {
          if (typeof newIndex === 'number' && typeof oldIndex === 'number') {
            const listNew: [] = JSON.parse(JSON.stringify(list.value))
            const currentRow = listNew.splice(oldIndex, 1)[0]!
            listNew.splice(newIndex, 0, currentRow)
            list.value = []
            nextTick(() => {
              list.value = listNew
            })
          }
        }
      })
  })
}

const delRow = (row: FormType) => {
  list.value = list.value.filter((item) => item !== row)
}

const show = () => {
  visible.value = true
  setTimeout(() => {
    initSortable()
  }, 200)
}

const hide = () => {
  visible.value = false
  clearForm()
}

defineExpose({
  show,
  hide
})
</script>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0px;
}
:deep(.el-button) {
  height: 39px !important;
  border-radius: 6px !important;
}
</style>
